package com.qy.common.base;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.qy.common.mvp.IPresenter;
import com.qy.common.mvp.IView;
import com.qy.common.widget.MMLoading;

import org.simple.eventbus.EventBus;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 基类
 * 复制版
 * initView();
 * initListener();
 *
 * @param <T>
 * @param <P>
 */

public abstract class BaseActivity<T extends ViewBinding, P extends IPresenter> extends AppCompatActivity implements IView {
    protected final String TAG = this.getClass().getSimpleName();
    protected T vb;
    protected P mPresenter;
    protected Context mContext;
    protected AppCompatActivity mActivity;
    private MMLoading mmLoading;
    protected CompositeDisposable compositeDisposable;

    @Nullable
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mActivity = this;
        //设置竖屏
        setVertical();
        //viewBinding 将布局初始化
        initContentView();
        mPresenter = getPresenter();
        //如果要使用eventBus请将此方法返回true
        if (useEventBus()) EventBus.getDefault().register(this);//注册到事件主线
        initAny();
    }

    protected void setVertical() {
        try {
            //设置坚屏 一定要放到try catch里面，否则会崩溃
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理App第一次安装后打开，退到后台再次进入应用时候，之前的页面不保留，App重新启动。问题主要出现在华为手机上。
     * https://blog.csdn.net/nsacer/article/details/80346843
     *
     * @param nonRoot
     * @return
     */
    @Override
    public boolean moveTaskToBack(boolean nonRoot) {
        return super.moveTaskToBack(true);
    }

    /**
     * viewBinding 将布局初始化
     */
    private void initContentView() {
        Type superclass = getClass().getGenericSuperclass();
        Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
        try {
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
            vb = (T) method.invoke(null, getLayoutInflater());
            setContentView(vb.getRoot());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (mPresenter == null) {
            mPresenter = getPresenter();
        }
    }

    @Override
    public void showLoading(boolean cancelable) {
        if (mmLoading != null) mmLoading.dismiss();
        MMLoading.Builder builder = new MMLoading.Builder(this)
                .setMessage("加载中...")
                .setShowMessage(false)
                .setCancelable(cancelable)
                .setCancelOutside(false);
        mmLoading = builder.create();
        mmLoading.show();
    }

    @Override
    public void showLoading() {
        if (mmLoading != null) mmLoading.dismiss();
        if (mContext == null) return;
        MMLoading.Builder builder = new MMLoading.Builder(this)
                .setShowMessage(false)
                .setCancelable(true)
                .setCancelOutside(false);
        mmLoading = builder.create();
        mmLoading.show();
    }

    @Override
    public void hideLoading() {
        if (mmLoading != null && mmLoading.isShowing()) mmLoading.dismiss();
    }

    protected void addSubscribe(Disposable disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);//将所有subscription放入,集中处理
    }

    protected void unSubscribe() {
        if (compositeDisposable != null) {
            compositeDisposable.clear();//保证activity结束时取消所有正在执行的订阅
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.onDestroy();//释放资源
        if (useEventBus())//如果要使用eventbus请将此方法返回true
            EventBus.getDefault().unregister(this);
        this.mPresenter = null;
        hideLoading();
        unSubscribe();//解除订阅
        this.compositeDisposable = null;
    }

    /**
     * 是否使用eventBus,默认为不使用(false)，
     *
     * @return
     */
    protected boolean useEventBus() {
        return false;
    }

    protected abstract void initAny();

    protected abstract P getPresenter();

}
